from __future__ import absolute_import
from lxml import etree
import fnmatch
import logging
logger = logging.getLogger('pkgr.groups')
from pkgr.group import Group

class Groups(object):
    """ TODO: This is an ordered dict. id -> group; [group, ...]
    """
    
    def __init__(self):
        self.list = []
        self.idmap = {}
        
    def get_groups(self):
        return self.list
        
    def search_by_id(self, id):
        return self.idmap.get(id, None)
        
    def search_by_name_glob(self, name):
        matches = []
        name = name.lower()
        for group in self.get_groups():
            if fnmatch.fnmatch(group.get_name().lower(), name):
                matches.append(group)
        return matches
        
    def add_group(self, group):
        self.idmap[group.get_id()] = group
        self.list.append(group)
        
    @classmethod
    def from_xml(cls, d):
        groups = cls()
        root = etree.XML(d)
        n = 0
        for group in root:
            # simple copy from xml
            id = group.find('id')
            # XXX: apparently there are some without ids
            if id is None:
                continue
            
            n += 1
            
            id = id.text
            name = group.find('name').text
            
            newgroup = Group(id, name)
            newgroup.description = group.find('description').text
            
            
            # parse the "default" value. ?? whether the group is default ??
            default = group.find('default')
            if default is None or default.text == "false":
                newgroup.default =  False
            else:
                newgroup.default = True
            
            # parse the uservisible value
            uservisible = group.find('uservisible')
            if uservisible is None or uservisible.text == "false":
                newgroup.uservisible = False
            else:
                newgroup.uservisible = True
             
            # ?
            langonly = group.find('langonly')
            if langonly is not None:
                newgroup.langonly = langonly.text
                
                
            # build the package map
            for package in group.findall('.//packagereq'):
                newgroup.add_package(package.text, package.get('type'))
                
            groups.add_group(newgroup)
            
        logger.debug('Parsed %s groups', n)
        return groups   